package com.yiwei.ydd.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yiwei.ydd.Application;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.Const;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.util.AppDownloadManager;
import com.yiwei.ydd.util.CleanMessageUtil;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.DownloadUtil;
import com.yiwei.ydd.util.FileUtils;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.PreferenceUtils;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.V19FrameLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class SettingActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_login_logout)
    TextView btnLoginLogout;
    @BindView(R.id.btn_tips_switch)
    ImageView btnTipsSwitch;
    @BindView(R.id.btn_change_pass)
    LinearLayout btnChangePass;
    @BindView(R.id.btn_change_phone)
    LinearLayout btnChangePhone;
    @BindView(R.id.btn_about)
    LinearLayout btnAbout;
    @BindView(R.id.btn_point)
    LinearLayout btnPoint;
    @BindView(R.id.txt_version)
    TextView txtVersion;
    @BindView(R.id.btn_check_update)
    LinearLayout btnCheckUpdate;
    @BindView(R.id.btn_clear)
    LinearLayout btnClear;
    @BindView(R.id.txt_gesture)
    TextView txtGesture;
    @BindView(R.id.btn_gesture_pass)
    LinearLayout btnGesturePass;

    private Unbinder unbiner;
    private boolean tipsOpen = false;
    private AppDownloadManager appDownloadManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtVersion.setText("v" + Util.getVersion(this) + "版本");
        txtTitle.setText("设置");

    }

    public void getLogout() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getLogout().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    UserInfoGlobal.setIsOpenGuesture(false);
                    aCache.clear();
                    btnLoginLogout.setText("登录");
                    UserInfoGlobal.logout();
                    ToastUtil.makeText(this, "退出成功");
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_gesture_pass, R.id.btn_change_pass, R.id.btn_tips_switch, R.id.btn_login_logout, R.id.btn_back, R.id.btn_change_phone, R.id.btn_about, R.id.btn_point, R.id.btn_check_update, R.id.btn_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_login_logout:
                if (UserInfoGlobal.isLogin()) {
                    getLogout();
                } else {
                    Util.startActivity(this, LoginActivity.class);
                }
                break;
            case R.id.btn_tips_switch:
                btnTipsSwitch.setImageResource(tipsOpen ? R.mipmap.img_setting_off : R.mipmap.img_setting_on);
                tipsOpen = !tipsOpen;
                break;
            case R.id.btn_change_pass:
                if (Util.getIsLogin(this)) {


                    if (UserInfoGlobal.getIsSetPayPass()) {
                        Util.startActivity(this, HasSetTransactionActivity.class);
                    } else {
                        Util.startActivity(this, TransationSetStepOneActivity.class);
                    }
                }
                break;
            case R.id.btn_gesture_pass:
                Util.startActivity(this, GestureSettingActivity.class);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_change_phone:
                if (Util.getIsLogin(this))
                    Util.startActivity(this, ChangePhoneActivity.class);
                break;
            case R.id.btn_about:
                Util.startActivity(this, AboutUsActivity.class);
                break;
            case R.id.btn_point:
                break;
            case R.id.btn_check_update:
                checkUpdate();
//                Dialog.showDefaultDialog(this, "", "发现新版本，是否更新？", "取消", "立即更新", false, new Dialog.DialogDefaultClickListener() {
//                    @Override
//                    public void confirm() {
//
//                    }
//
//                    @Override
//                    public void cancel() {
//
//                    }
//                });
                break;
            case R.id.btn_clear:
                Dialog.showDefaultDialog(this, "", "是否确定清除缓存？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {
                        CleanMessageUtil.clearAllCache(Application.getInstance());
                    }
                });
                break;
        }
    }


    /**
     * 检查版本
     */
    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String url = PreferenceUtils.getString(this, "download_url", "");


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {
//                isFirstTips = false;

                //注册下载监听
                appDownloadManager = new AppDownloadManager(this);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    /**
     * 获取权限回调 兼容6.0
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                appDownloadManager.initDownloadManager();
            } else {
                // 获取权限失败
                ToastUtil.makeText(this, "获取权限失败~");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserInfoGlobal.isLogin()) {
            btnLoginLogout.setText("退出当前账号");
        } else {
            btnLoginLogout.setText("登录");
        }
        if (UserInfoGlobal.getIsOpenGuesture()) {
            txtGesture.setText("已开启");
        } else {
            txtGesture.setText("未开启");
        }
        if (appDownloadManager != null) {
            return;
        }
        checkUpdate();
    }
}
